/** 调拨管理 */

import React, {useEffect, useState} from 'react'
import {Button, Space, message, TreeSelect, Modal, Form, Input} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {connect, history} from 'umi'
import {PlusOutlined} from '@ant-design/icons'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import Permissions from '@/components/Permissions'
import CustomTable from '@/components/Table'
import {
	allocationnoCancel,
	getAllocationnoList,
} from '@/service/storage/allocation'
import {getAllCitys, getCompany} from '@/service/common'
import {translateDataToTree} from '@/utils/common'
import {getCompanyScope} from '@/service/system/company'

const {TextArea} = Input
interface DataType {
	showCancelButton: any
	id: string
	allocationCode: string
	orgId: number
	moveInCompany: number
	moveOutCityName: string
	moveInCityName: string
	allocationStatus: number | string
}
interface CityOption {
	value: string | number
	label: string
	children?: CityOption[]
}
const formItemLayout = {
	labelCol: {flex: '120px'},
	wrapperCol: {flex: '1'},
}

const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const allocation = (props: any) => {
	const [form] = Form.useForm()
	const [dataSourse, setDataSourse] = useState<any[]>([])
	const [searchData, setSearchData] = useState({})
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [id, setId] = useState<string>('')
	// 城市
	const [citysList, setCitysList] = useState<CityOption[]>([])
	const [companyData, setCompanyData] = useState([])
	const [allCompanyData, setAllCompanyData] = useState([])
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	// 初始化-城市
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res.data)
			}
		})
	}

	/** 获取公司数据（带权限） */
	const onCompany = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	/** 获取所有公司数据 */
	const onAllCompany = () => {
		getCompanyScope().then((res: any) => {
			const list = translateDataToTree(res.data)
			setAllCompanyData(list as any)
		})
	}
	useEffect(() => {
		onAllCompany()
		getCitysFun()
		onCompany()
	}, [props?.user?.orgId])

	/** 获取调拨列表 */
	const getData = () => {
		setLoading(true)
		getAllocationnoList({...params, ...searchData})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				} else {
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])

	/** 点击详情及编辑事件 */
	const onDetails = (type: string, record: DataType) => {
		history.push({
			pathname: `/storage/allocation/${type}`,
			query: {
				id: record?.id,
			},
		})
	}

	const columns: ColumnsType<DataType> = [
		{
			title: '调拨批次',
			dataIndex: 'allocationCode',
			align: 'center',
			width: 100,
		},
		{
			title: '调出公司名称',
			dataIndex: 'orgId',
			align: 'center',
			width: 150,
			render: (text) => (
				<>
					{text ? (
						<TreeSelect
							value={text}
							disabled
							dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
							treeDefaultExpandAll
							fieldNames={fieldNames}
							treeDataSimpleMode
							treeData={companyData}
						/>
					) : (
						'-'
					)}
				</>
			),
		},
		{
			title: '调出城市',
			dataIndex: 'moveOutCityName',
			align: 'center',
			width: 100,
		},
		{
			title: '调入公司名称',
			dataIndex: 'moveInCompany',
			align: 'center',
			width: 150,
			render: (text) => (
				<>
					{text ? (
						<TreeSelect
							value={text}
							disabled
							dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
							treeDefaultExpandAll
							fieldNames={fieldNames}
							treeDataSimpleMode
							treeData={allCompanyData}
						/>
					) : (
						'-'
					)}
				</>
			),
		},
		{
			title: '调入城市',
			dataIndex: 'moveInCityName',
			align: 'center',
			width: 100,
		},
		{
			title: '调拨状态',
			dataIndex: 'allocationStatus',
			align: 'center',
			width: 100,
			render: (text) => {
				if (text === 1) {
					return '调拨中'
				}
				if (text === 2) {
					return '已完成'
				}
				if (text === 3) {
					return '已取消'
				}
				return ''
			},
		},
		{
			title: '发起时间',
			dataIndex: 'createTime',
			align: 'center',
			width: 160,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			width: 200,
			fixed: 'right',
			render: (text: any, record) => (
				<Space size={12}>
					<Permissions permissionID="amc_storage_allocation_view">
						<Button
							type="link"
							onClick={() => {
								onDetails('view', record)
							}}>
							查看
						</Button>
					</Permissions>
					{record?.allocationStatus === 1 ? (
						<>
							<Permissions permissionID="amc_storage_allocation_edit">
								<Button
									type="link"
									onClick={() => {
										onDetails('edit', record)
									}}>
									填写费用项
								</Button>
							</Permissions>
						</>
					) : null}
					{record?.allocationStatus === 1 ? (
						<>
							{record?.showCancelButton ? (
								''
							) : (
								<Permissions permissionID="amc_storage_allocation_delete">
									<Button
										type="link"
										onClick={() => {
											setId(record?.id)
											setIsModalOpen(true)
										}}>
										取消
									</Button>
								</Permissions>
							)}
						</>
					) : null}
				</Space>
			),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '调拨批次',
					name: 'allocationCode',
					key: 'allocationCode',
					placeholder: '请输入调拨批次',
				},
				{
					type: 'treeSelect',
					key: 'orgId',
					name: 'orgId',
					label: '调出公司名称',
					placeholder: '请选择调出公司名称',
					keys: 'id',
					title: 'name',
					treeData: companyData,
				},
				{
					type: 'treeSelect',
					key: 'moveInCompany',
					name: 'moveInCompany',
					label: '调入公司名称',
					placeholder: '请选择调入公司名称',
					keys: 'id',
					title: 'name',
					treeData: allCompanyData,
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'select',
					key: 'allocationStatus',
					name: 'allocationStatus',
					label: '调拨状态',
					placeholder: '请选择调拨状态',
					keys: 'value',
					title: 'title',
					items: [
						{value: 1, title: '调拨中'},
						{value: 2, title: '已完成'},
						{value: 3, title: '已取消'},
					],
				},
				{
					type: 'time',
					subtype: 'date',
					label: '发起日期',
					name: 'createTimeStr',
					key: 'createTimeStr',
				},
				{
					type: 'cascader',
					key: 'cityId',
					name: 'cityId',
					label: '调出城市',
					placeholder: '请选择调出城市',
					fieldNames: {
						label: 'name',
						value: 'id',
						children: 'cityInfoList',
					},
					items: citysList,
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'cascader',
					key: 'moveInCity',
					name: 'moveInCity',
					label: '调入城市',
					placeholder: '请选择调入城市',
					fieldNames: {
						label: 'name',
						value: 'id',
						children: 'cityInfoList',
					},
					items: citysList,
				},
				{},
				{},
			],
		},
	]
	const onFinish = (values: any) => {
		setSearchData({
			...values,
			createTimeStr: values?.createTimeStr
				? moment(values?.createTimeStr).format('YYYY-MM-DD')
				: '',
			cityId: values?.cityId ? values?.cityId?.[1] : '',
			moveInCity: values?.moveInCity ? values?.moveInCity?.[1] : '',
			current: 1,
			size: 10,
		})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const handleOk = async () => {
		const value = await form.validateFields()
		if (value) {
			allocationnoCancel({id, ...value})
				.then((res: any) => {
					if (res.success) {
						message.success(res.msg)
						setIsModalOpen(false)
						form.resetFields()
						getData()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}
	}

	return (
		<div className={styles.allocation}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<div className={styles.btnlist}>
					<Space size={12}>
						<Permissions permissionID="amc_storage_allocation_add">
							<Button
								icon={<PlusOutlined />}
								type="primary"
								ghost
								size="small"
								onClick={() => {
									history.push('/storage/allocation/add')
								}}>
								新增数据
							</Button>
						</Permissions>
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
			<Modal
				title="取消调拨"
				destroyOnClose
				open={isModalOpen}
				onOk={handleOk}
				onCancel={() => {
					setIsModalOpen(false)
					form.resetFields()
				}}>
				<Form
					form={form}
					name="enclosure"
					layout="horizontal"
					labelCol={{flex: '90px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off">
					<Form.Item
						label="取消原因"
						name="cancelReason"
						rules={[
							{required: true, message: '请填写取消调拨原因'},
						]}>
						<TextArea
							maxLength={200}
							placeholder="请填写取消调拨原因，不超过200个字符"
							autoSize={{minRows: 3, maxRows: 6}}
						/>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	)
}

export default connect(({user}: any) => ({user}))(allocation)
